import { createSlice } from "@reduxjs/toolkit";

type list = Array<number>

const counter = createSlice({
  // 命名空间，name值回座位action type的前缀
  name:'counter',
  // 初始化状态
  initialState:{
    count:0,
    list:[] as list,
    name:'魏忠贤',
  users:{
    user:'',
    password:'',
  },
  },
  // 1、定义reducer更新状态函数  2、组件中dispatch使用的action函数
  // 内置了immutable.js插件
  reducers:{
    add(state) {
      state.count++
    },
    sub(state) {
      state.count--
    },
    pus(state) {
      state.list.push(Math.floor(Math.random()*100))
    },
    del(state,action) {
      state.list.splice(action.payload,1)
    },
    changeName(state,action) {
      state.name = action.payload
    }
  }
})

// 导出action函数
export const {add,sub,pus,del,changeName} = counter.actions  

// 定义异步action => 处理异步请求
export const subAsync = () => {
  return async(dispatch: any) => {
    setTimeout(() => dispatch(sub()),3000)
  }
}

// 导出reducer，创建store
export default counter.reducer